#include "querytree.h"

#include "simplequery.h"

QueryTree::QueryTree()
{
    type = SIMPLE;
    left_query_tree = NULL;
    right_query_tree = NULL;
    query = NULL;
}

QueryTree::QueryTree(QueryType type,QueryTree * left_query_tree, QueryTree * right_query_tree)
{
    this->type = type;

    if(left_query_tree != NULL) this->left_query_tree = left_query_tree->clone();
    else this->left_query_tree = NULL;

    if(right_query_tree != NULL) this->right_query_tree = right_query_tree->clone();
    else this->right_query_tree = NULL;

    this->query = NULL;
}

QueryTree::QueryTree(SimpleQuery * query)
{
    type = SIMPLE;

    if(query != NULL) this->query = query->clone();
    else this->query = NULL;

    left_query_tree = NULL;
    right_query_tree = NULL;
}

QueryTree::~QueryTree()
{
    delete query; query = NULL;
    delete left_query_tree; left_query_tree = NULL;
    delete right_query_tree; right_query_tree = NULL;
}

QueryTree::QueryTree(const QueryTree& other)
{
    type = other.type;

    if(other.left_query_tree == NULL) left_query_tree = NULL;
    else left_query_tree =  other.left_query_tree->clone();

    if(other.right_query_tree == NULL) right_query_tree = NULL;
    else right_query_tree = other.right_query_tree->clone();

    if(other.query == NULL) query = NULL;
    else query = other.query->clone();
}

QueryTree* QueryTree::getLeftQueryTree() const
{
    return left_query_tree;
}

void QueryTree::setType(QueryType type)
{
    this->type = type;
}

void QueryTree::setSimpleQuery(SimpleQuery * query)
{
    delete this->query; this->query = NULL;
    if(query != NULL) this->query = query->clone();
}

void QueryTree::setRightQueryTree(QueryTree * query)
{
    delete right_query_tree; right_query_tree = NULL;
    if(query != NULL) right_query_tree = query->clone();
}

void QueryTree::setLeftQueryTree(QueryTree * query)
{
    delete left_query_tree; left_query_tree = NULL;
    if(query != NULL) left_query_tree = query->clone();
}

QueryType QueryTree::getQueryType()
{
    return type;
}

SimpleQuery* QueryTree::getSimpleQuery() const
{
    return query;
}

QueryTree* QueryTree::getRightQueryTree() const
{
    return right_query_tree;
}

string QueryTree::toString()
{
    string str = "{\n";
    if(type == SIMPLE){
        if(query != NULL) str = str + query->toString();
    }else if(type == UNION){
        if(left_query_tree != NULL) str = str + left_query_tree->toString() + "\n";
        str = str + "UNION \n";
        if(right_query_tree != NULL) str = str + right_query_tree->toString();
    }else if(type == INTERSECTION){
        if(left_query_tree != NULL) str = str + left_query_tree->toString() + "\n";
        str = str + "INTERSECTION \n";
        if(right_query_tree != NULL) str = str + right_query_tree->toString();
    }// if-else

    return str + "\n}";
}

QueryTree * QueryTree::clone()
{
    return new QueryTree(*this);
}

